package edu.dayu.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import edu.dayu.mapper.ImageMapper;
import edu.dayu.pojo.Image;
import edu.dayu.service.ImageService;
import edu.dayu.util.ConstantOssPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

@Service
public class ImageServiceImpl implements ImageService {
    @Autowired
    private ImageMapper imageMapper;


    @Override
    public PageInfo<Image> ImageList(Image image) {
        PageHelper.startPage(image.getPageNum(),image.getPageSize());
        List<Image> images = imageMapper.ImageList(image);
        PageInfo<Image> imagePageInfo = new PageInfo<>(images);
        return imagePageInfo;
    }

    @Override
    public void ImageUpdate(Image image) {
        imageMapper.ImageUpdate(image);
    }

    @Override
    public void ImageInsert(Image image) {
        imageMapper.ImageInsert(image);
    }

    @Override
    public void ImageDelete(Image image) {
        imageMapper.ImageDelete(image);
    }

    @Override
    public String upload(MultipartFile file,String fileName) {
        // Endpoint以深圳为例，其它Region请按实际情况填写。
        String endpoint = ConstantOssPropertiesUtils.EDNPOINT;
        String accessKeyId = ConstantOssPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantOssPropertiesUtils.SECRET;
        String bucketName = ConstantOssPropertiesUtils.BUCKET;
        try {
            OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 上传文件流。
            InputStream inputStream = file.getInputStream();
//            String fileName = file.getOriginalFilename();
//            //生成随机唯一值，使用uuid，添加到文件名称里面
//            String uuid = UUID.randomUUID().toString().replaceAll("-","");
//            fileName = uuid+fileName;
            //按照当前日期，创建文件夹，上传到创建文件夹里面
            //  2021/02/02/01.jpg
//            String timeUrl = new DateTime().toString("yyyy/MM/dd");
//            fileName = timeUrl+"/"+fileName;
            //调用方法实现上传
            oss.putObject(bucketName,fileName,inputStream);
            // 关闭OSSClient。
            oss.shutdown();
            //上传之后文件路径
            // https://dayu-club.oss-cn-beijing.aliyuncs.com/01.jpg
            String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
            //返回
//            Image image = new Image();
//            image.setImage(fileName);
//            imageMapper.ImageInsert(image);
            return url;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
}
